from django.contrib import admin
from django.utils.html import format_html
from django.urls import path
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from django.contrib import messages
from django.db.models import Count, Q
from django.utils.safestring import mark_safe
import json
import threading
from .models import Category, Product, ApiLog, SyncTask
from .services import EbayApiService
from .token_manager import TokenManager
from django.contrib.admin import SimpleListFilter

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    """类目管理"""
    list_display = ['category_id', 'category_name', 'level', 'parent_name', 'children_count', 'product_count', 'actions_column']
    list_filter = ['level', 'leaf_category', 'created_at']
    search_fields = ['category_id', 'category_name', 'category_path']
    ordering = ['level', 'category_id']
    list_per_page = 50
    
    def get_queryset(self, request):
        return super().get_queryset(request).select_related().prefetch_related()
    
    def parent_name(self, obj):
        """显示父类目名称"""
        if obj.parent:
            return obj.parent.category_name
        return "无"
    parent_name.short_description = "父类目"
    
    def children_count(self, obj):
        """显示子类目数量"""
        count = obj.children.count()
        if count > 0:
            return format_html(
                '<a href="/admin/ebay/category/?parent_id={}">{} 个子类目</a>',
                obj.category_id, count
            )
        return "0"
    children_count.short_description = "子类目"
    
    def product_count(self, obj):
        """显示商品数量"""
        count = Product.objects.filter(ebay_category_id=obj.category_id).count()
        if count > 0:
            return format_html(
                '<a href="/admin/ebay/product/?ebay_category_id={}">{} 个商品</a>',
                obj.category_id, count
            )
        return "0"
    product_count.short_description = "商品数量"
    
    def actions_column(self, obj):
        """操作列"""
        buttons = []
        
        # 添加同步商品按钮
        sync_url = f'/admin/ebay/category/sync_products/{obj.category_id}/'
        buttons.append(
            f'<a href="{sync_url}" class="button">同步商品</a>'
        )
        
        # 如果有子类目，添加查看子类目按钮
        if obj.children.exists():
            children_url = f'/admin/ebay/category/?parent_id={obj.category_id}'
            buttons.append(
                f'<a href="{children_url}" class="button">查看子类目</a>'
            )
        
        return format_html(' '.join(buttons))
    actions_column.short_description = "操作"
    
    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('sync_categories/', self.admin_site.admin_view(self.sync_categories), name='ebay_sync_categories'),
            path('sync_products/<str:category_id>/', self.admin_site.admin_view(self.sync_products), name='ebay_sync_products'),
            path('check_token/', self.admin_site.admin_view(self.check_token), name='ebay_check_token'),
            path('get_token/', self.admin_site.admin_view(self.get_token), name='ebay_get_token'),
        ]
        return custom_urls + urls
    
    def sync_products(self, request, category_id):
        """同步指定类目的商品"""
        if request.method == 'POST':
            try:
                max_items = int(request.POST.get('max_items', 1000))
                
                def run_sync():
                    try:
                        # 先检查token
                        token_manager = TokenManager()
                        token = token_manager.get_token()
                        if not token:
                            print("❌ 没有有效的token，同步失败")
                            return
                        
                        print(f"✅ 使用token进行同步: {token[:20]}...")
                        service = EbayApiService()
                        service.sync_products_by_category(category_id, max_items)
                    except Exception as e:
                        print(f"❌ 同步过程中出错: {e}")
                
                # 在后台线程中运行同步
                thread = threading.Thread(target=run_sync)
                thread.daemon = True
                thread.start()
                
                messages.success(request, f"类目 {category_id} 的商品同步任务已启动，请稍后查看结果")
                return HttpResponseRedirect("/admin/ebay/product/")
                    
            except Exception as e:
                messages.error(request, f"操作失败: {e}")
                return HttpResponseRedirect("/admin/ebay/category/")
        
        # GET请求 - 显示同步页面
        try:
            category = Category.objects.get(category_id=category_id)
        except Category.DoesNotExist:
            messages.error(request, f"类目 {category_id} 不存在")
            return HttpResponseRedirect("/admin/ebay/category/")
        
        # 获取类目下的商品数量
        product_count = Product.objects.filter(ebay_category_id=category_id).count()
        
        context = {
            'title': f'同步类目 {category.category_name} 的商品',
            'category': category,
            'product_count': product_count,
        }
        return render(request, 'admin/ebay/sync_products.html', context)
    
    def check_token(self, request):
        """检查token状态"""
        try:
            token_manager = TokenManager()
            token_info = token_manager.get_token_info()
            
            return JsonResponse({
                'success': True,
                'token_info': token_info
            })
        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': str(e)
            })
    
    def get_token(self, request):
        """获取新的token"""
        try:
            token_manager = TokenManager()
            token = token_manager.get_token()
            
            if token:
                return JsonResponse({
                    'success': True,
                    'message': 'Token获取成功',
                    'token_info': token_manager.get_token_info()
                })
            else:
                return JsonResponse({
                    'success': False,
                    'error': 'Token获取失败'
                })
        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': str(e)
            })
    
    def sync_categories(self, request):
        """同步所有类目"""
        if request.method == 'POST':
            try:
                # 执行同步
                def run_sync():
                    try:
                        # 先检查token
                        token_manager = TokenManager()
                        token = token_manager.get_token()
                        if not token:
                            print("❌ 没有有效的token，同步失败")
                            return
                        else:
                            token_manager._save_token(token)
                        print(f"✅ 使用token进行同步: {token[:20]}...")
                        service = EbayApiService()
                        service.sync_all_categories()
                    except Exception as e:
                        print(f"❌ 同步过程中出错: {e}")
                
                # 在后台线程中运行同步
                thread = threading.Thread(target=run_sync)
                thread.daemon = True
                thread.start()
                
                messages.success(request, "类目同步任务已启动，请稍后查看结果")
                return HttpResponseRedirect("/admin/ebay/category/")
                    
            except Exception as e:
                messages.error(request, f"操作失败: {e}")
                return HttpResponseRedirect("/admin/ebay/category/")
        
        # GET请求 - 显示同步页面
        # 获取统计信息
        category_stats = Category.objects.aggregate(
            total=Count('id'),
            level1=Count('id', filter=Q(level=1)),
            level2=Count('id', filter=Q(level=2)),
            level3=Count('id', filter=Q(level=3)),
        )
        
        # 检查token状态
        token_info = None
        try:
            token_manager = TokenManager()
            token_info = token_manager.get_token_info()
        except Exception as e:
            token_info = {'status': 'error', 'message': str(e)}
        
        context = {
            'title': '同步eBay类目',
            'category_stats': category_stats,
            'token_info': token_info,
        }
        return render(request, 'admin/ebay/sync_categories.html', context)

class Level1CategoryFilter(SimpleListFilter):
    """一级类目过滤器"""
    title = '一级类目'
    parameter_name = 'level1'

    def lookups(self, request, model_admin):
        categories = Category.objects.filter(level=1).order_by('category_name')
        return [(cat.category_id, cat.category_name) for cat in categories]

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(ebay_category_id=self.value())
        return queryset

class Level2CategoryFilter(SimpleListFilter):
    """二级类目过滤器"""
    title = '二级类目'
    parameter_name = 'level2'

    def lookups(self, request, model_admin):
        level1_id = request.GET.get('level1')
        if level1_id:
            categories = Category.objects.filter(parent_id=level1_id, level=2).order_by('category_name')
            return [(cat.category_id, cat.category_name) for cat in categories]
        return []

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(ebay_category_id=self.value())
        return queryset

class Level3CategoryFilter(SimpleListFilter):
    """三级类目过滤器"""
    title = '三级类目'
    parameter_name = 'level3'

    def lookups(self, request, model_admin):
        level2_id = request.GET.get('level2')
        if level2_id:
            categories = Category.objects.filter(parent_id=level2_id, level=3).order_by('category_name')
            return [(cat.category_id, cat.category_name) for cat in categories]
        return []

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(ebay_category_id=self.value())
        return queryset

class DateRangeFilter(SimpleListFilter):
    """发布时间过滤器"""
    title = '发布时间'
    parameter_name = 'date_range'

    def lookups(self, request, model_admin):
        return [
            ('today', '今天'),
            ('yesterday', '昨天'),
            ('this_week', '本周'),
            ('last_week', '上周'),
            ('this_month', '本月'),
            ('last_month', '上月'),
        ]

    def queryset(self, request, queryset):
        from datetime import datetime, timedelta
        now = datetime.now()
        
        if self.value() == 'today':
            return queryset.filter(created_at__date=now.date())
        elif self.value() == 'yesterday':
            yesterday = now - timedelta(days=1)
            return queryset.filter(created_at__date=yesterday.date())
        elif self.value() == 'this_week':
            start = now - timedelta(days=now.weekday())
            return queryset.filter(created_at__date__gte=start.date())
        elif self.value() == 'last_week':
            start = now - timedelta(days=now.weekday() + 7)
            end = now - timedelta(days=now.weekday() + 1)
            return queryset.filter(created_at__date__range=[start.date(), end.date()])
        elif self.value() == 'this_month':
            return queryset.filter(created_at__year=now.year, created_at__month=now.month)
        elif self.value() == 'last_month':
            last_month = now.replace(day=1) - timedelta(days=1)
            return queryset.filter(created_at__year=last_month.year, created_at__month=last_month.month)
        return queryset

class CategoryTypeFilter(SimpleListFilter):
    """蓝海/红海类目过滤器"""
    title = '类目类型'
    parameter_name = 'category_type'

    def lookups(self, request, model_admin):
        return [
            ('blue', '蓝海类目'),
            ('red', '红海类目'),
        ]

    def queryset(self, request, queryset):
        if self.value() == 'blue':
            # 蓝海类目：商品数量少于100的类目
            blue_categories = Category.objects.annotate(
                product_count=Count('product')
            ).filter(product_count__lt=100).values_list('category_id', flat=True)
            return queryset.filter(ebay_category_id__in=blue_categories)
        elif self.value() == 'red':
            # 红海类目：商品数量大于等于100的类目
            red_categories = Category.objects.annotate(
                product_count=Count('product')
            ).filter(product_count__gte=100).values_list('category_id', flat=True)
            return queryset.filter(ebay_category_id__in=red_categories)
        return queryset

class EbayProductAdmin(admin.ModelAdmin):
    """商品管理"""
    list_display = [
        'item_id', 'title_display', 'category_name', 'ebay_category_id',
        'current_price', 'currency', 'condition', 'listing_type',
        'buy_it_now_price', 'seller_username', 'seller_feedback_score',
        'gallery_image', 'view_link', 'shipping_cost', 'location',
        'start_time', 'end_time', 'watch_count', 'bid_count',
        'created_at', 'updated_at'
    ]
    
    list_filter = [
        Level1CategoryFilter,
        Level2CategoryFilter,
        Level3CategoryFilter,
        'condition',
        'listing_type',
        'currency',
        'location',
        DateRangeFilter,
        CategoryTypeFilter,
        'updated_at'
    ]
    
    search_fields = [
        'item_id',
        'title',
        'category__category_name',
        'ebay_category_id',
        'seller_username',
        'location'
    ]
    
    readonly_fields = [
        'item_id', 'title', 'category_name', 'ebay_category_id',
        'current_price', 'currency', 'condition', 'listing_type',
        'buy_it_now_price', 'seller_username', 'seller_feedback_score',
        'gallery_image', 'view_link', 'shipping_cost', 'location',
        'start_time', 'end_time', 'watch_count', 'bid_count',
        'created_at', 'updated_at'
    ]
    
    class Media:
        css = {
            'all': ('admin/css/category_filter.css',)
        }
        js = ('admin/js/category_filter.js',)
    
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.select_related('category')
    
    def changelist_view(self, request, extra_context=None):
        """重写changelist_view来传递类目数据"""
        # 获取所有一级类目
        level1_categories = Category.objects.filter(level=1).annotate(
            product_count=Count('product')
        ).order_by('category_name')
        
        # 获取选中的一级类目
        selected_level1 = request.GET.get('level1')
        level2_categories = []
        level3_categories = []
        selected_level2 = None
        selected_level3 = None
        
        if selected_level1:
            # 获取对应的二级类目
            level2_categories = Category.objects.filter(
                parent_id=selected_level1,
                level=2
            ).annotate(
                product_count=Count('product')
            ).order_by('category_name')
            
            # 获取选中的二级类目
            selected_level2 = request.GET.get('level2')
            if selected_level2:
                # 获取对应的三级类目
                level3_categories = Category.objects.filter(
                    parent_id=selected_level2,
                    level=3
                ).annotate(
                    product_count=Count('product')
                ).order_by('category_name')
                
                selected_level3 = request.GET.get('level3')

        extra_context = extra_context or {}
        extra_context.update({
            'level1_categories': level1_categories,
            'level2_categories': level2_categories,
            'level3_categories': level3_categories,
            'selected_level1': selected_level1,
            'selected_level2': selected_level2,
            'selected_level3': selected_level3,
        })
        
        return super().changelist_view(request, extra_context=extra_context)
    
    def category_name(self, obj):
        """显示类目名称"""
        if obj.category:
            return obj.category.category_name
        return "-"
    category_name.short_description = '类目名称'
    
    def title_display(self, obj):
        return format_html(
            '<a href="{}" target="_blank">{}</a>',
            obj.view_item_url,
            obj.title[:80] + "..." if len(obj.title) > 80 else obj.title
        )
    title_display.short_description = '标题'
    
    def gallery_image(self, obj):
        if obj.gallery_url:
            return format_html(
                '<img src="{}" style="max-width:100px;max-height:100px;" />',
                obj.gallery_url
            )
        return '-'
    gallery_image.short_description = '图片'
    
    def view_link(self, obj):
        return format_html(
            '<a href="{}" target="_blank">查看</a>',
            obj.view_item_url
        )
    view_link.short_description = '链接'


class ApiLogAdmin(admin.ModelAdmin):
    """API日志管理"""
    list_display = ['api_type', 'operation', 'status', 'execution_time', 'created_at']
    list_filter = ['api_type', 'status', 'created_at']
    search_fields = ['operation', 'error_message']
    ordering = ['-created_at']
    readonly_fields = ['api_type', 'operation', 'request_data', 'response_data', 
                      'status', 'error_message', 'execution_time', 'created_at']
    
    def has_add_permission(self, request):
        return False
    
    def has_change_permission(self, request, obj=None):
        return False


class SyncTaskAdmin(admin.ModelAdmin):
    """同步任务管理"""
    list_display = ['task_type', 'category_id', 'status', 'progress', 'started_at', 'completed_at']
    list_filter = ['task_type', 'status', 'created_at']
    search_fields = ['category_id', 'error_message']
    ordering = ['-created_at']
    readonly_fields = ['task_type', 'category_id', 'total_items', 'processed_items',
                      'error_message', 'started_at', 'completed_at', 'created_at']
    
    def progress(self, obj):
        """显示进度"""
        if obj.total_items > 0:
            percentage = (obj.processed_items / obj.total_items) * 100
            return f"{obj.processed_items}/{obj.total_items} ({percentage:.1f}%)"
        return f"{obj.processed_items}/0"
    progress.short_description = "进度"
    
    def has_add_permission(self, request):
        return False
    
    def has_change_permission(self, request, obj=None):
        return False


# 注册模型到admin
admin.site.register(Product, EbayProductAdmin)
admin.site.register(ApiLog, ApiLogAdmin)
admin.site.register(SyncTask, SyncTaskAdmin)

# 自定义admin站点标题
admin.site.site_header = 'eBay管理系统'
admin.site.site_title = 'eBay管理'
admin.site.index_title = 'eBay数据管理'
